//
//  EnemyNode.m
//  iFly
//
//  Created by User-10 on 12/7/14.
//  Copyright (c) 2014 TeamDifferent. All rights reserved.
//

#import "EnemyNode.h"
#import "Constants.h"
#import "CharacterNode.h"
#import "SoundHandler.h"

@implementation EnemyNode

+(instancetype)enemyWithImageNamed:(NSString *)image andPosition:(CGPoint)position andHealth:(NSInteger)health andPointsForKill:(NSInteger)points {
    
    EnemyNode* enemy = [self spriteNodeWithImageNamed:image];
    
    enemy.position = position;
    enemy.health = health;
    enemy.pointsForKill = points;
    
    [enemy setupPhysicsBodyProperties];
    
    return enemy;
}

-(void)setupPhysicsBodyProperties {
    //Adding SpriteKit physicsBody for collision detection
    self.physicsBody  = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width/4 center:self.anchorPoint];
    self.physicsBody.categoryBitMask = obstacleCategory;
    self.physicsBody.affectedByGravity = NO;
    self.physicsBody.dynamic = YES;
    self.physicsBody.contactTestBitMask = characterCategory|shieldCategory;
    self.physicsBody.collisionBitMask = 0;
    self.physicsBody.usesPreciseCollisionDetection = YES;
    self.name = @"enemy";
}

-(void) wasHit {
    [[SoundHandler sharedSoundPlayer] playSoundWithName:@"explosion_small" andType:@"caf"];
    self.health--;
    
    if (self.health == 0) {
        //play explosion sound
        
        SKEmitterNode *emitter =  [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"Fire" ofType:@"sks"]];
        emitter.position = self.position;
        emitter.name = @"FireEmitter";
        [self.parent addChild:emitter];        
        
        SKAction* fadeEmitter = [SKAction fadeAlphaTo:0.0 duration:2];
        SKAction* remove = [SKAction removeFromParent];
        SKAction* sequence = [SKAction sequence:@[fadeEmitter, remove]];
        [emitter runAction:sequence];
       
        CharacterNode* character= (CharacterNode*)[self.parent childNodeWithName:@"character"];
        [character addScore:self.pointsForKill];
       
        [self removeFromParent];
    }
}

-(void) moveToPosition:(CGPoint) position {
    CGPoint target = CGPointMake(0, self.position.y);\
    
    int minDuration = 2.0;
    int maxDuration = 4.0;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = (arc4random() % rangeDuration) + minDuration;
    
    SKAction* move = [SKAction moveTo:target duration:actualDuration];
    SKAction* moveDone = [SKAction removeFromParent];
    [self runAction:[SKAction sequence:@[move, moveDone]]];
}

@end
